#include "plane.h"

#include "ray.h"

#include <cmath>
#include <cstdio>
#include <limits>

namespace raytrace {

Plane::Plane(Vector3Arg normal, float dist, const Material* material)
  : Primitive(Vector3::scale(normal, dist), material),
    normal_(normal),
    dist_(dist) {
}

bool Plane::IntersectsWith(const Ray& r, float& d) const {
  float dot = Vector3::dot(normal_, r.d_);
  if (fabsf(dot) > std::numeric_limits<float>::epsilon()) {
		d = -(Vector3::dot(normal_, r.o_) + dist_) / dot;
    return (d > 0);
  }
  return false;
}

Vector3 Plane::NormalAt(Vector3Arg pt) const {
  // TODO: flip normal if normal_.dot(r.d_) > 0
  return normal_;
}

Vector3 Plane::GetRandomPoint() const {
  // TODO: make it random
  return Vector3::scale(normal_, dist_);
}
}
